package merisis.util;

import java.util.Collection;
import java.util.Iterator;

import org.apache.solr.util.OpenBitSet;

public class BitUtil {

	/**
	 * list and format a string for the object of OpenBitSet.
	 */
	public static void format(StringBuilder sb, OpenBitSet bs, String sep) {

		if (bs == null) {
			sb.append("null");
			return;
		}

		long i = bs.nextSetBit(0);
		if (i >= 0) {
			sb.append(i);
			i = bs.nextSetBit(i + 1);
			while (i >= 0) {
				sb.append(sep);
				sb.append(i);
				i = bs.nextSetBit(i + 1);
			}
		}
	}

	public static void format(StringBuilder sb, long[] bs, String sep) {

		if (bs == null || bs.length == 0)
			return;

		sb.append(bs[0]);
		for (int i = 1; i < bs.length; i++) {
			sb.append(sep);
			sb.append(bs[i]);
		}
	}

	public static String toString(long[] array) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		if (array != null) {
			format(sb, array, ",");
		}
		sb.append("}");

		return sb.toString();
	}

	public static String toString(long[][] array) {

		StringBuilder sb = new StringBuilder();
		sb.append("{");
		if (array != null) {
			for (long[] ay : array) {
				sb.append("{");
				format(sb, ay, ",");
				sb.append("}");
			}
		}
		sb.append("}");

		return sb.toString();
	}

	public static String toString(OpenBitSet bs) {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		if (bs != null) {
			format(sb, bs, ",");
		}
		sb.append("}");
		return sb.toString();
	}

	public static String toStringOfBitSetCollection(Collection<OpenBitSet> c) {

		StringBuilder sb = new StringBuilder();
		sb.append('{');

		while (true) {

			if (c == null)
				break;

			Iterator<OpenBitSet> itr = c.iterator();
			if (itr.hasNext()) {
				sb.append('{');
				BitUtil.format(sb, itr.next(), ",");
				sb.append('}');
			}

			while (itr.hasNext()) {
				sb.append(',');
				sb.append('{');
				BitUtil.format(sb, itr.next(), ",");
				sb.append('}');
			}

			break;
		}
		sb.append('}');

		return sb.toString();
	}

	public static OpenBitSet bitsetOrArray(OpenBitSet bs, long[] array) {

		for (int i = 0; i < array.length; i++) {
			bs.set(array[i]);
		}

		return bs;
	}

	public static OpenBitSet bitsetClearArray(OpenBitSet bs, long[] array) {

		for (int i = 0; i < array.length; i++) {
			bs.clear(array[i]);
		}

		return bs;
	}

	public static long[] toArray(OpenBitSet s) {

		if (s == null)
			return null;

		long[] array = new long[(int) s.cardinality()];
		int k = 0;
		for (long i = s.nextSetBit(0); i >= 0; i = s.nextSetBit(i + 1)) {

			array[k] = i;
			k++;
		}

		return array;
	}
}
